<?php
/**
 * Created by PhpStorm.
 * User: lingyun
 * Date: 2017-11-17
 * Time: 15:51
 * @desc   商城后台 -- 库存管理
 */
namespace app\mall\controller;
use controller\BasicAdmin;
use service\DataService;
use think\Db;
use think\Request;
class Estimate extends BasicAdmin{
    /**
     * @Author lignyun
     * @Desc   营业额统计 -- 门店形成数据对比
     * 默认查看本月的数据对比统计
     * 2018-05-17   原先的全部统计有错误
     */
    public function index_old(){
        $post = input('param.');
        $condition = " where order_status=4";      //订单已经完成
        //统计对应的时间
        if(empty($post['daterange'])){
            $date = $this->getMonth(0);
//            $condition .= " and addtime>".$date['start']." and addtime<".$date['end'];
        }else{
            if(isset($post['daterange']) && $post['daterange'] !== '') {
                // list($start, $end) = explode('-', str_replace(' ', '', $get['date']));
                list($start, $end) = explode(' - ', $post['daterange']);
                $start = $start."  00:00:00";		$end = $end." 23:59:59";
                $start = strtotime($start);			$end = strtotime($end);
                $date['start'] = $start;     $date['end'] = $end;   $date['day'] = round(($end-$start)/3600/24);
//                $condition .= " and addtime>".$start." and addtime<".$end;
            }
        }

        $store = Db::name('store')->where(['status'=>1,'is_deleted'=>0])->field('id,title,addtime')->select();     //门店列表
        //统计对应门店
        if(!empty($post['store'])){
            $condition .=" and store_id=".$post['store'];
        }
        //查询门店短时间内以及指定的门店的营业额数据
        $sql = "select t2.days,t3.begin_day,t3.end_day,t3.store_id,c.title,t3.pay_day,IFNULL(t3.amount,0) all_amount from (SELECT @cdate := date_add(@cdate,interval+1  day) days from (SELECT @cdate := '".date('Y-m-d',$date['start'])."' from ys_order limit ".$date['day'].") t1) t2 LEFT JOIN (select '".date('Y-m-d',$date['end'])."' as end_day,store_id,date_add('".date('Y-m-d',$date['end'])."',interval -".$date['day']." day) begin_day,date_format(FROM_UNIXTIME(pay_time,'%Y-%m-%d'),'%Y-%m-%d') pay_day,sum(final_amount-tuihuo_amount) amount from ys_order ".$condition." and '".date('Y-m-d',$date['end'])."'<=date_add(date_format(FROM_UNIXTIME(pay_time,'%Y-%m-%d'),'%Y-%m-%d'),interval 30 day) group by store_id,date_format(FROM_UNIXTIME(pay_time,'%Y-%m-%d'),'%Y-%m-%d')) t3 on t2.days=t3.pay_day LEFT JOIN ys_store as c on t3.store_id=c.id";
        $list = Db::query($sql);                    //组合的数据
halt($sql);
        $day = array_values(array_unique(array_column($list, 'days')));        //取出日期 -- 数组
//        $days = implode(',',$day);        //取出日期 -- 字符串
        $data = array();        //组合数据
//        halt($days);
//        foreach($store as $k => $v){
//            foreach($list as $k1 => $v1){
//                if($v['id'] == $v1['store_id']){        //门店id
//                    if(isset($data[$v['title']])){
//                        array_push($data[$v['title']],$v1['all_amount']);
//                    }else{
//                        $data[$v['title']] = array();
//                        array_push($data[$v['title']],$v1['all_amount']);
//                    }
//                }else{
//                    if(isset($data[$v['title']])){
//                        array_push($data[$v['title']],0);
//                    }else{
//                        $data[$v['title']] = array();
//                        array_push($data[$v['title']],0);
//                    }
//                }
//            }
//        }
        foreach($store as $k => $v){
            foreach($list as $k1 => $v1){
                if($v['id'] == $v1['store_id']){        //门店id
                    if(isset($data[$v['id']])){
                        $data[$v['id']]['name'] = $v['title'];
                        $data[$v['id']]['type'] = 'line';
                        $data[$v['id']]['stack'] = '总量';
                        if(isset($data[$v['id']]['data'])){
                            $key = array_search($v1['days'],$day);
                            $data[$v['id']]['data'][$key] = $v1['all_amount'];
                        }else{
                            $data[$v['id']]['data'] = array();
                            $key = array_search($v1['days'],$day);
                            $data[$v['id']]['data'][$key] = $v1['all_amount'];
                        }
                    }else{
                        $data[$v['id']] = array();
                        $data[$v['id']]['name'] = $v['title'];
                        $data[$v['id']]['type'] = 'line';
                        $data[$v['id']]['stack'] = '总量';
                        if(isset($data[$v['id']]['data'])){
                            $key = array_search($v1['days'],$day);
                            $data[$v['id']]['data'][$key] = $v1['all_amount'];
                        }else{
                            $data[$v['id']]['data'] = array();
                            $key = array_search($v1['days'],$day);
                            $data[$v['id']]['data'][$key] = $v1['all_amount'];
                        }
                    }
                }else{
                    if(isset($data[$v['id']])){
                        $data[$v['id']]['name'] = $v['title'];
                        $data[$v['id']]['type'] = 'line';
                        $data[$v['id']]['stack'] = '总量';
                        if(isset($data[$v['id']]['data'])){
                            $key = array_search($v1['days'],$day);
                            $data[$v['id']]['data'][$key] = !empty($data[$v['id']]['data'][$key])?$data[$v['id']]['data'][$key]:'0.00';
                        }else{
                            $data[$v['id']]['data'] = array();
                            $key = array_search($v1['days'],$day);
                            $data[$v['id']]['data'][$key] = !empty($data[$v['id']]['data'][$key])?$data[$v['id']]['data'][$key]:'0.00';
                        }
                    }else{
                        $data[$v['id']] = array();
                        $data[$v['id']]['name'] = $v['title'];
                        $data[$v['id']]['type'] = 'line';
                        $data[$v['id']]['stack'] = '总量';
                        if(isset($data[$v['id']]['data'])){
                            $key = array_search($v1['days'],$day);
                            $data[$v['id']]['data'][$key] = !empty($data[$v['id']]['data'][$key])?$data[$v['id']]['data'][$key]:'0.00';
                        }else{
                            $data[$v['id']]['data'] = array();
                            $key = array_search($v1['days'],$day);
                            $data[$v['id']]['data'][$key] = !empty($data[$v['id']]['data'][$key])?$data[$v['id']]['data'][$key]:'0.00';
                        }
                    }
                }
            }
        }
//        $store_list = implode(',',array_column($store, 'title'));
        $store_list = array_column($store, 'title');
        $this->assign('data',json_encode(array_values($data)));     //重建索引
        $this->assign('days',json_encode($day));
        $this->assign('store',json_encode(array_values($store_list)));
        $this->assign('date',$date);
        return $this->fetch('index');
    }

    /**
     * @Author  lingyun
     * @Desc    门店交易统计
     */
    public function index(){
        $post = input('param.');
        if(empty($post['daterange'])){
            $time = $this->getMonth(0);
//            $condition .= " and addtime>".$date['start']." and addtime<".$date['end'];
        }else{
            if(isset($post['daterange']) && $post['daterange'] !== '') {
                // list($start, $end) = explode('-', str_replace(' ', '', $get['date']));
                list($start, $end) = explode(' - ', $post['daterange']);
                $start = $start."  00:00:00";		$end = $end." 23:59:59";
                $time['start'] = strtotime($start);			$time['end'] = strtotime($end);
            }
        }

        $map = " and a.pay_time>".$time['start']." and a.pay_time<".$time['end'];
        $store = db('store')->where(['is_deleted'=>0])->column('id,title');

        $sql = "select  sum(a.final_amount-a.tuihuo_amount) as totalmoney,b.id,b.title, count(*) as num from ys_order as a left join ys_store as b on a.store_id=b.id WHERE a.order_status>=4 ".$map." group by b.id ORDER BY b.id asc";

        $db = Db::query($sql);

        foreach ($db as $key => $value) {
            $ndb[$value['id']]['totalmoney'] = $value['totalmoney'];
            $ndb[$value['id']]['num'] = $value['num'];
            $ndb[$value['id']]['title'] = $value['title'];
        }

        ksort($ndb);

        foreach ($store as $value => $v) {
            if (!isset($ndb[$value])) {
                $ndb[$value]['num'] = '0';
                $ndb[$value]['totalmoney'] = '0';
                $ndb[$value]['title'] = $v;
            }
        }
        $max_amount = 0;            //最高交易额
        $max_num = 0;               //最高交易量
        foreach ($ndb as $key => $value) {
            $title[] = (string)$value['title'];
            $totalmoney[] = $value['totalmoney'];
            $totalnum[] = (string)$value['num'];
            if($value['totalmoney']>$max_amount){
                $max_amount = $value['totalmoney'];
            }
            if($value['num']>$max_num){
                $max_num = $value['num'];
            }
        }

        $this->assign('title', json_encode($title));
        $this->assign('totalmoney', json_encode($totalmoney));
        $this->assign('totalnum', json_encode($totalnum));
        $this->assign('max_amount', $max_amount);
        $this->assign('max_num', $max_num);
        $this->assign('time',$time);
        return $this->fetch();
    }

    /**
     * @Author lignyun
     * @Desc   获取今天的时间戳
     */
    private function getToday(){
        $beginToday=mktime(0,0,0,date('m'),date('d'),date('Y'));
        $endToday=mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
        return ['start'=>$beginToday,'end'=>$endToday];
    }

    /**
     * @Author lignyun
     * @Desc   获取制定的月份的时间戳
     * @param int $month
     */
    private function getMonth($month=0){
        $y = date('Y',time());		//获取年份
        if($month == 0){
            $m = date('m',time());
            $month = $y."-".$m;
            $start=strtotime($month)-1;
            $end=mktime(23, 59, 59, date('m', strtotime($month))+1, 00);
            $day = round(($end-$start)/3600/24);
            return ['start'=>$start,'end'=>$end,'day'=>$day];
        }else{
            $m = $y."-".$month;
            $start=strtotime($m)-1;
            $end=mktime(23, 59, 59, date('m', strtotime($m))+1, 00);
            return ['start'=>$start,'end'=>$end];
        }
    }
    /**
     * @Author   lingyun
     * @Desc     获取今年的时间戳
     * @return   [type]   [description]
     */
    public function getYear(){
        $date = date('Y',time());		//2017-12-08 19:54:18
        $start = strtotime($date."-1-1 00:00:00");
        $end = strtotime($date."-12-31 23:59:59");
        return ['start'=>$start,'end'=>$end];
    }

}